export default {
  namespaced : true,
  state : {
    cartList : JSON.parse(uni.getStorageSync('cartList') || '[]')
  },
  mutations : {
    addCart(state,goods) {
      let findRestult = state.cartList.find(item => item.goods_id == goods.goods_id)
      if(findRestult) {
        findRestult.goods_count ++
      } else {
        state.cartList.push(goods)
      }
      uni.setStorageSync('cartList',JSON.stringify(state.cartList))
    },
    updateState(state,goods) {
      let findResult = state.cartList.find(item => item.goods_id == goods.goods_id)
      if(findResult) {
        findResult.goods_state = !goods.goods_state
      }
      uni.setStorageSync('cartList',JSON.stringify(state.cartList))
    },
    updateNum(state,goods) {
      let findResult = state.cartList.find(item => item.goods_id == goods.goods_id)
      if(findResult) {
        findResult.goods_count = goods.goods_count
      }
      uni.setStorageSync('cartList',JSON.stringify(state.cartList))
    },
    deleteItem(state,id) {
      state.cartList =  state.cartList.filter(item => item.goods_id !== id)
      uni.setStorageSync('cartList',JSON.stringify(state.cartList))
    },
    checkAllGoodsState(state,type) {
      state.cartList.forEach(item => item.goods_state = type)
      uni.setStorageSync('cartList',JSON.stringify(state.cartList))
    }
  },
  getters : {
    total(state) {
      let c = 0
      state.cartList.forEach(item => c += item.goods_count)
      return c
    },
    checkoutAmount(state) {
      return state.cartList.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count,0)
    },
    checkGoodsPrice(state) {
      return state.cartList.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2)
    }
    
  }
}